﻿namespace Ngs.MetaData
{
    using System;
    using System.Collections.Generic;
    using Ngs.MetaData;

    public class MetaType : MetaObject
    {
        public const string GenericTypeName = "GenericType";

        #region Constructors

        public MetaType(string name)
            : this(name, MetaVisibility.Public)
        {
        }

        public MetaType(string name, MetaVisibility visibility)
            : base(name)
        {
            this.MetaDataType = MetaTypeDataType;
            this.Visibility = visibility;
            // Self register with Metadata System;
            //MetaCatalog catalog = SystemApplication.Default.Catalog;
            // catalog.RegisterType(this);
        }

        internal MetaType()
            : this(GenericTypeName)
        {
        }

        #endregion

        #region Propeties

        public MetaVisibility Visibility { get; private set; }

        #endregion

        public override string ToString()
        {
            return this.Name + " - " + this.Visibility.ToString();
        }

        #region Static Members

        private static Dictionary<Type, MetaType> cache = new Dictionary<Type, MetaType>();

        public readonly static MetaType GenericType = new MetaType();

        public readonly static MetaType MetaTypeDataType = CreateType(typeof(MetaType));

        internal static MetaType ReflectedType(Type type)
        {
            return new MetaType(type.Name, MetaDataExtensions.ReflectionType(type));
        }

        public static MetaType CreateType(Type type)
        {
            MetaType metaType;
            if (cache.TryGetValue(type, out metaType))
            {
                return metaType;
            }

            metaType = ReflectedType(type);
            cache.Add(type, metaType);
            return metaType;
        }
        #endregion
    }
}
